﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using Medianamik.UI.Controls;
using Medianamik.UI.Web.Shop.Data.Repositories;
using StructureMap;

namespace Medianamik.UI.Web.Shop.Controls
{
    public class ProductsInCategoriesDropDownList: ProductsInCategoriesDropDownList<Data.Interfaces.ICategory>
    {
    }

    public class ProductsInCategoriesDropDownList<TCategory> : DropDownListManyToMany
        where TCategory : Data.Interfaces.ICategory
    {
        private readonly ICategoryRepository<TCategory> _categoryRepository = ObjectFactory.GetInstance<ICategoryRepository<TCategory>>();

        protected override void CreateControlHierarchy(bool pUseDataSource)
        {
            ManyToManyDropDownList.CssClass = "SelectList";
            Controls.Add(ManyToManyDropDownList);

            if (pUseDataSource)
            {
                var selectedValues = DataSource as IEnumerable<Guid> ?? Enumerable.Empty<Guid>();

                var productCategories = _categoryRepository.GetProductCategoriesWithParent();

                    if (productCategories.Count > 0)
                    {
                        foreach (var productCategory in productCategories)
                        {
                            var item = new ListItem(productCategory.Name, productCategory.NodeId.ToString());
                            ManyToManyDropDownList.Items.Add(item);
                            item.Selected = selectedValues.Any(v => v.Equals(productCategory.NodeId));
                        }
                    }
                    ManyToManyDropDownList.Items.Insert(0, new ListItem("", Guid.Empty.ToString()));
            }
        }
    }
}
